#include<iostream>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<cstring>
 #include <sys/stat.h>
#include <fcntl.h>
#define BUFFER_SIZE 128
#define PORT 9090
struct SendMe {
    int num;              // 包序号
    char buffer[1024];    // 数据缓冲区
};

int main() {
    // 创建 UDP 套接字
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd == -1) {
        perror("socket error:");
        exit(-1);
    }

    // 绑定 IP 和端口
    struct sockaddr_in localAddress;
    memset(&localAddress, 0, sizeof(localAddress));
    localAddress.sin_family = AF_INET;
    localAddress.sin_port = htons(PORT);
    localAddress.sin_addr.s_addr = htonl(INADDR_ANY);
    
    int ret = bind(sockfd, reinterpret_cast<const sockaddr*>(&localAddress), sizeof(localAddress));
    if (ret != 0) {
        perror("bind error");
        close(sockfd);
        exit(-1);
    }

    SendMe t1;

    // 接收文件名
    ssize_t size = recvfrom(sockfd, &t1.num, sizeof(int), 0, NULL, NULL);
    if (size <= 0) {
        perror("recvfrom error (num):");
        close(sockfd);
        exit(-1);
    }

    size = recvfrom(sockfd, t1.buffer, sizeof(t1.buffer), 0, NULL, NULL);
    if (size <= 0) {
        perror("recvfrom error (filename):");
        close(sockfd);
        exit(-1);
    }

    // 打开文件
    if (t1.num == 1) {
        char *filename = t1.buffer;
        int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0644);
        if (fd == -1) {
            perror("open error:");
            close(sockfd);
            exit(-1);
        }

        // 清空缓冲区，准备接收文件数据
        memset(t1.buffer, 0, sizeof(t1.buffer));

        while (true) {
            // 接收文件数据块
            ssize_t bytesReceived = recvfrom(sockfd, &t1.num, sizeof(int), 0, NULL, NULL);
            if (bytesReceived <= 0) {
                perror("recvfrom error (num):");
                close(fd);
                close(sockfd);
                exit(-1);
            }

            bytesReceived = recvfrom(sockfd, t1.buffer, sizeof(t1.buffer), 0, NULL, NULL);
            if (bytesReceived <= 0) {
                perror("recvfrom error (file content):");
                close(fd);
                close(sockfd);
                exit(-1);
            }

            if (strcmp(t1.buffer, "EOF") == 0) {
                // 接收到 "EOF" 表示文件传输结束
                break;
            }

            // 将接收到的数据写入文件
            ssize_t bytesWritten = write(fd, t1.buffer, bytesReceived);
            if (bytesWritten == -1) {
                perror("write error:");
                close(fd);
                close(sockfd);
                exit(-1);
            }

            // 清空缓冲区，准备接收下一块数据
            memset(t1.buffer, 0, sizeof(t1.buffer));
        }

        // 关闭文件描述符
        close(fd);
    }

    // 关闭套接字
    close(sockfd);
    return 0;
}








